package smecta.client.print.util;

import lombok.extern.slf4j.Slf4j;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;

@Slf4j
public class ProcessUtil {

    public static void quitProcesses(String appName) {
        List<String> pids = findProcessIds(appName);
        for (String pid : pids) {
            try {
                Runtime.getRuntime().exec("taskkill /F /PID " + pid);
                log.info("Killed process with PID: {}", pid);
            } catch (Exception e) {
                log.info("Killed process with PID: {}， e:{}", pid, e);
            }
        }
    }

    private static List<String> findProcessIds(String appName) {
        List<String> pids = new ArrayList<>();
        try {
            Process p = Runtime.getRuntime().exec("tasklist");
            BufferedReader reader = new BufferedReader(new InputStreamReader(p.getInputStream()));
            String line;
            while ((line = reader.readLine()) != null) {
                if (line.contains(appName)) {
                    String[] tokens = line.split("\\s+");
                    pids.add(tokens[1]); // 进程ID通常在输出的第二列
                }
            }
            reader.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return pids;
    }
}
